package com.joesem.sale.client.network

import com.google.gson.GsonBuilder
import com.jiaxing.sale.client.BuildConfig
import com.joesem.sale.client.MyApplication
import com.joesem.sale.client.db.LoginTable
import com.joesem.sale.client.network.log.LogInterceptor
import okhttp3.Dispatcher
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit


object NetworkTools {

    val apiService: Api by lazy {
        getApi()
    }

    private fun getApi(): Api {
        val retrofitBuilder = Retrofit.Builder()
            .baseUrl(BuildConfig.IP)
            .client(okHttpClient)
            .addConverterFactory(GsonConverterFactory.create(GsonBuilder().create()))
        return retrofitBuilder.build().create(Api::class.java)
    }

    private val okHttpClient by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
        val dispatcher = Dispatcher();
        dispatcher.maxRequestsPerHost = 10;
        OkHttpClient.Builder()
            .connectTimeout(30, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)
            .dispatcher(dispatcher)
            .addInterceptor(LogInterceptor())
            .addInterceptor(HeaderInterceptor())
            .retryOnConnectionFailure(true)
            .build()
    }
}

class HeaderInterceptor : Interceptor {

    private fun getVersionName(): String {
        return try {
            MyApplication.instance
                .packageManager
                .getPackageInfo(MyApplication.instance.packageName, 0).versionName
        } catch (e: Exception) {
            ""
        }
    }

    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val builder = request.newBuilder().apply {
            addHeader("Authorization", "Bearer ${LoginTable.table.getToken()}")
        }
        return chain.proceed(builder.build())
    }


}